//
//  WLSMSCodeInputView.swift
//  HengYouCai
//
//  Created by wll on 2018/5/25.
//  Copyright © 2018年 lwj. All rights reserved.
//  验证码输入视图

private let labWH: Int = 36

import UIKit

class WLSMSCodeInputView: UIView {

    deinit {
        NotificationCenter.default.removeObserver(self)
        debugPrint("WLSMSCodeInputView dealloc")
    }
    
    ///输入完成回调
    public var inputCompletionHandler: ((_ str: String)->Void)?
    
    private var num = 1
    private var labArr = [UILabel]()
    
    //构造函数 懒的扩展 只支持此两种构造方式
    @discardableResult convenience init(_ frame: CGRect, _ num: Int) {
        self.init(frame: frame)
        self.num = num
        self.createUI()
        self.tf.becomeFirstResponder()
    }
    
    @discardableResult convenience init(_ num: Int) {
        self.init(CGRect.zero, num)
    }
    
    ///创建UI
    private func createUI () {
        self.addSubview(self.tf)
        self.layer.borderColor = Normal_999Color.cgColor
        self.layer.borderWidth = 1
        for _ in 1...self.num {
            let lab = UILabel()
            lab.layer.borderWidth = self.layer.borderWidth
            lab.layer.borderColor = self.layer.borderColor
            lab.textAlignment = .center
            self.addSubview(lab)
            self.labArr.append(lab)
        }

        ///监听
//        unowned var strongSelf = self
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
//        block方式会造成循环引用 暂时未找到解决办法
//        NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: nil, queue: nil) { (notification) in
//
//            if let str: NSString = self.tf.text as NSString?, let length = self.tf.text?.count {
//                for (index,lab) in self.labArr.enumerated() {
//                    if index < length {
//                        lab.text = str.substring(with: NSRange(location: index, length: 1))
//                    }else{
//                        lab.text = nil
//                    }
//                    if length == self.num {
//                        self.tf.resignFirstResponder()
//                    }
//                    if length > self.num {
//                        self.tf.text = str.substring(to: self.num)
//                    }
//                    //回调
//                    self.inputCompletionHandler?(self.tf.text ?? "")
//                }
//            }
//        }
    }
    
    func textDidChange() {
        if let str: NSString = self.tf.text as NSString?, let length = self.tf.text?.count {
            for (index,lab) in self.labArr.enumerated() {
                if index < length {
                    lab.text = str.substring(with: NSRange(location: index, length: 1))
                }else{
                    lab.text = nil
                }
                if length == self.num {
                    self.tf.resignFirstResponder()
                }
                if length > self.num {
                    self.tf.text = str.substring(to: self.num)
                }
                //回调
                self.inputCompletionHandler?(self.tf.text ?? "")
            }
        }
    }
    
    ///布局UI
    override func layoutSubviews() {
        super.layoutSubviews()
        self.bounds = CGRect(x: 0, y: 0, width: 1+(labWH-1)*self.num, height: labWH)
        for (index, lab) in labArr.enumerated() {
            lab.frame = CGRect(x: index*(labWH - 1), y: 0, width: labWH, height: labWH)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.tf.becomeFirstResponder()
    }
    
    private let tf: UITextField = {
        let temp = UITextField(frame: CGRect.zero)
        temp.isHidden = true
        temp.keyboardType = .numberPad
        return temp
    }()

}
